<?php
/**
 * StatZone default team controller
 * 
 * @package    USS.StatZone
 * @subpackage Components
 * @link www.ugenix.co.za www.statzone.co.za
 * @license		Commercial
 * @author Salie Hendricks
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.controller' );

/**
 * @package		USS
 * @subpackage	StatZone
 */
class StatZoneControllerTeam extends JController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

        // Register Extra tasks
		$this->registerTask( 'add'  , 	'edit' );
        $this->registerTask( 'apply',		'save' );
	}

    /**
	 * Display the list of teams
	 */
	function display()
	{
		global $mainframe;

		$db =& JFactory::getDBO();

		$context			= 'com_statzone.team.list.';
		$filter_order		= $mainframe->getUserStateFromRequest( $context.'filter_order',		'filter_order',		'name',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $context.'filter_order_Dir',	'filter_order_Dir',	'',			'word' );
		$filter_provid		= $mainframe->getUserStateFromRequest( $context.'filter_provid',		'filter_provid',		'',			'int' );
        $filter_clubid		= $mainframe->getUserStateFromRequest( $context.'filter_clubid',		'filter_clubid',		'',			'int' );
		$search				= $mainframe->getUserStateFromRequest( $context.'search',			'search',			'',			'string' );

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0, 'int' );

		$where = array();
        
		if ($filter_provid) {
			$where[] = 'c.provinceid = ' . (int) $filter_provid;
		}
        if ($filter_clubid) {
			$where[] = 't.clubid = ' . (int) $filter_clubid;
		}
        
		if ($search) {
			$where[] = ' LOWER(t.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}

		$where		= count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '';
		$orderby	= ' ORDER BY '. $filter_order .' '. $filter_order_Dir ;

		// get the total number of records
		$query = 'SELECT COUNT(*)'
		. ' FROM #__statzone_teams AS t'
		. ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
        . ' INNER JOIN #__statzone_province AS p ON p.id = c.provinceid'
        . ' INNER JOIN #__content AS content ON c.contentid = content.id'
		. $where
		;
        
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );

		$query = 'SELECT t.id as id, t.name as name, c.id as clubid, p.id as provinceid, content.title as club_name, p.name as province_name, t.description as description'
		. ' FROM #__statzone_teams AS t'
		. ' INNER JOIN #__statzone_clubs AS c ON c.id = t.clubid'
		. ' INNER JOIN #__statzone_province AS p ON p.id = c.provinceid'
        . ' INNER JOIN #__content AS content ON c.contentid = content.id'
		. $where
		. $orderby
        ;
        //echo $query;
        
       	$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
       	$rows = $db->loadObjectList();
        
		$javascript		= 'onchange="document.adminForm.submit();"';
		
        // ________build list of provinces ________
        $sql = 'SELECT id as provinceid, name'
		. ' FROM #__statzone_province'
		;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}
    
        $javascript		= 'onchange="submitform();"';
        $provincelist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Province -' ), 'provinceid', 'name' );
		$provincelist			= array_merge( $provincelist, $db->loadObjectList() );
		$lists['provinceid']		= JHTML::_('select.genericlist',   $provincelist, 'provinceid', 'class="inputbox" size="1"','provinceid', 'name', $row->provinceid );
        $lists['filter_provid']		= JHTML::_('select.genericlist',   $provincelist, 'filter_provid', 'class="inputbox" size="1"' . $javascript, 'provinceid', 'name', $filter_provid );

        // ________build list of clubs________
        $sql = 'SELECT c.id as clubid, content.title AS name'
		. ' FROM #__statzone_clubs AS c'
		. ' INNER JOIN #__content AS content ON c.contentid = content.id'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        
        ;
        
        if($filter_provid)
        {
            $sql = $sql . ' WHERE c.provinceid = '.(int) $filter_provid;
        }
        $sql = $sql . ' ORDER BY name';
        
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}

		$clublist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Club -' ), 'clubid', 'name' );
		$clublist			= array_merge( $clublist, $db->loadObjectList() );
		$lists['clubid']		= JHTML::_('select.genericlist',   $clublist, 'clubid', 'class="inputbox" size="1"','clubid', 'name', $row->clubid );
        $lists['filter_clubid']		= JHTML::_('select.genericlist',   $clublist, 'filter_clubid', 'class="inputbox" size="1"'.$javascript,'clubid', 'name', $filter_clubid );

		// table ordering
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;

		// search filter
		$lists['search']= $search;

		require_once(JPATH_COMPONENT.DS.'views'.DS.'teams.php');
		StatZoneViewTeams::teams( $rows, $pageNav, $lists );
	}
    
	/**
	 * display the edit form
	 * @return void
	 */
	function edit()
	{
        $db		=& JFactory::getDBO();
		$user	=& JFactory::getUser();

        if ($this->_task == 'edit') 
        {
			$cid	= JRequest::getVar('cid', array(0), 'method', 'array');
			$cid	= array((int) $cid[0]);
		} 
        else 
        {
			$cid	= array( 0 );
		}

        $lists = array();
        
		$option = JRequest::getCmd('option');     
        
        $row =& JTable::getInstance('teams', 'Table');
		$row->load( $cid[0] );

        // ________build list of provinces ________
        $sql = 'SELECT id as provinceid, name'
		. ' FROM #__statzone_province'
		;
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone&c=team' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}
        
        //echo '$row->id='.$row->id;
        $javascript		= 'onchange="document.adminForm.task.value=\'edit&cid='.$row->id.'\';submitform();"';
        $ajaxCallback = 'onchange="document.forms[1].Submit.click();"';
		$provincelist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Province -' ), 'provinceid', 'name' );
		$provincelist			= array_merge( $provincelist, $db->loadObjectList() );
        if($row->id > 0 )
        {
            $sql = 'SELECT c.provinceid FROM #__statzone_teams t INNER JOIN #__statzone_clubs c ON c.id = t.clubid WHERE t.id = ' . $row->id;
            $provinceidforteam= $db->loadresult();
        }
        else
        {
            $provinceidforteam = $post['provinceid'];
        }
		$lists['provinceid']		= JHTML::_('select.genericlist',   $provincelist, 'provinceid', $ajaxCallback. 'class="inputbox" size="1"','provinceid', 'name', $provinceidforteam );

        // ________build list of clubs________
        $sql = 'SELECT c.id as clubid, content.title AS name'
		. ' FROM #__statzone_clubs AS c'
		. ' INNER JOIN #__content AS content ON c.contentid = content.id'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        ;
        
        if($provinceidforteam >0)
        {
            $sql = $sql . ' WHERE provinces.id = ' . $provinceidforteam ;
        }
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
			return JError::raiseWarning( 500, $db->getErrorMsg() );
		}

		$clublist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Club -' ), 'clubid', 'name' );
		$clublist			= array_merge( $clublist, $db->loadObjectList() );
		$lists['clubid']		= JHTML::_('select.genericlist',   $clublist, 'clubid', 'class="inputbox" size="1"','clubid', 'name', $row->clubid );

		$row =& JTable::getInstance('teams', 'Table');
		$row->load( $cid[0] );
        
        require_once(JPATH_COMPONENT.DS.'views'.DS.'teams.php');
		StatZoneViewTeams::singleTeam( $row, $lists);		
	}

	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
    
        // Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );

		// Initialize variables
		$db =& JFactory::getDBO();
        
		$post	= JRequest::get( 'post' );
		
        $row =& JTable::getInstance('teams', 'Table');

		if (!$row->bind( $post )) {
            echo 'Unable to bind: '. $row->getError();
			//return JError::raiseWarning( 500, $row->getError() );
		}
        
        if (!$row->check()) {
            echo 'check failed';
			//return JError::raiseWarning( 500, $row->getError() );
		}
         //save the province to the club table
        //if (!$row->store()) {
        //    echo 'Store() failed';
		//	//return JError::raiseWarning( 500, $row->getError() );
		//}
        //$row->checkin();
        
        $id= $post['id'];
        $name= $post['name'];
        $clubid = $post['clubid'];
        $description= $post['description'];
        if($id > 0)
        {
            $sql = 'UPDATE #__statzone_teams SET name=\''. $name . '\', clubid='. $clubid. ', description=\''. $description. '\' WHERE id = '. $id ;
            //echo 'Heres the SQL: ' . $sql;
            $db->execute($sql);
        }
        else
        {
            
            $sql = 'INSERT INTO #__statzone_teams (clubid,name,description) VALUES('.$clubid.',\'' . $name . '\', \''.$description.'\')';
            //echo 'Heres the SQL: ' . $sql;
            $db->setQuery($sql);
            if (!$db->query())
            {
                JError::raiseError( 500, $db->stderr() );
                return false;
            }
            $insertedId = $db->insertid();
                        
        }
                
        switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_statzone&c=team&task=edit&cid[]='. $row->id ;
				break;

			case 'save':
			default:
				$link = 'index.php?option=com_statzone&c=team';
				break;
		}

		$this->setRedirect( $link, JText::_( 'Item Saved' ) );
        
	}


	/**
	 * remove record(s)
	 * @return void
	 */
	function remove()
	{
        // Check for request forgeries
		JRequest::checkToken() or die( 'Invalid Token' );

		$this->setRedirect( 'index.php?option=com_statzone&c=team' );

		// Initialize variables
		$db		=& JFactory::getDBO();
		$cid	= JRequest::getVar( 'cid', array(), 'post', 'array' );
		$n		= count( $cid );
		JArrayHelper::toInteger( $cid );

		if ($n)
		{
			$query = 'DELETE FROM #__statzone_teams'
			. ' WHERE id = ' . implode( ' OR id = ', $cid )
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseWarning( 500, $row->getError() );
			}
		}

		$this->setMessage( JText::sprintf( 'Items removed', $n ) );
	}


	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_( 'Operation Cancelled' );
		$this->setRedirect( 'index.php?option=com_statzone&c=task', $msg );
	}
    
    /**
	 * Ajax call back function to update the list of clubs given the province id selected
	 * @return void
	 */
    function updateClublist()
    {
        $db		=& JFactory::getDBO();
		$user	=& JFactory::getUser();
        
        $provinceid = JRequest::getCmd('provinceid');
        //$provinceid = JRequest::getCmd('id');
        
        // import library
        jimport('joomla.utilities.simplexml');
        // create root node
        $xml = new JSimpleXMLElement('item', array('clublist' => $clublist));
        
        
        // ________build list of clubs________
        $sql = 'SELECT c.id as clubid, content.title AS name'
		. ' FROM #__statzone_clubs AS c'
		. ' INNER JOIN #__content AS content ON c.contentid = content.id'
		. ' INNER JOIN #__statzone_province AS provinces ON c.provinceid = provinces.id'
        ;
        
        if($provinceid > 0)
        {
            $sql = $sql . ' WHERE provinces.id = ' . $provinceid ;
        }
        $sql .= ' ORDER BY content.title'; 
		$db->setQuery($sql);
		if (!$db->query())
		{
			$this->setRedirect( 'index.php?option=com_statzone' );
            $inputrows =& $xml->addChild('responseData');
            //return JError::raiseWarning( 500, $db->getErrorMsg() );
            $inputrows->setData($db->getErrorMsg() );
            
            $document =& JFactory::getDocument();
            $document->setMimeEncoding('text/xml');
            
            echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
            echo $xml->toString();  
            return;
		}

		$clublist[]		= JHTML::_('select.option',  '0', JText::_( '- Select Club -' ), 'clubid', 'name' );
		$clublist			= array_merge( $clublist, $db->loadObjectList() );
		$lists['clubid']		= JHTML::_('select.genericlist',   $clublist, 'clubid', 'class="inputbox" size="1"','clubid', 'name', $row->clubid );
        
        
        //create the child node that will hold data
        $responseData =& $xml->addChild('responsedata');
        
        $responseData->setData($lists['clubid']);//'this is a test prov id = '.$provinceid . ' and teamid = '. $teamid);
        
        $document =& JFactory::getDocument();
        $document->setMimeEncoding('text/xml');
        //echo 'WASUPPPPPPP' ;
        echo '<?xml version="1.0" encoding="UTF-8" ?>'."\n";
        echo $xml->toString();          
               
        
    }
}
?>
